package com.dazzle.core.web.filter.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import com.dazzle.system.dao.SysResourceDao;
import com.dazzle.system.entity.SysResource;


//1 加载资源与权限的对应关系
public class MySecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
	//由spring调用
	public MySecurityMetadataSource(SysResourceDao sysResourceDao) {
		this.sysResourceDao = sysResourceDao;
		loadResourceDefine();
	}
	
	@Resource
	private SysResourceDao sysResourceDao;
	
	private static Map<String, Collection<ConfigAttribute>> resourceMap = new HashMap<String, Collection<ConfigAttribute>>();

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		// TODO Auto-generated method stub
		return null;
	}

	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return true;
	}
	//加载所有资源与权限的关系
	private void loadResourceDefine() {
		if(resourceMap.isEmpty()) {
			resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
			List<SysResource> resources = this.sysResourceDao.getAll();
			for (SysResource resource : resources) {
				Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
				//以权限名封装为Spring的security Object
				ConfigAttribute configAttribute = new SecurityConfig(resource.getResName());
				configAttributes.add(configAttribute);
				resourceMap.put(resource.getResUrl(), configAttributes);
			}
		}
		
//		Set<Entry<String, Collection<ConfigAttribute>>> resourceSet = resourceMap.entrySet();
//		Iterator<Entry<String, Collection<ConfigAttribute>>> iterator = resourceSet.iterator();
		
	}
	//返回所请求资源所需要的权限
	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		
		String requestUrl = ((FilterInvocation) object).getRequestUrl();
		System.out.println("requestUrl is " + requestUrl);
		if(resourceMap.isEmpty()) {
			loadResourceDefine();
		}
		return resourceMap.get(requestUrl);
	}
	
	//修改了权限之后,调用此方法把权限清除掉再加载
	public void reloadResourceDefine(){
		resourceMap.clear();
		loadResourceDefine();
	}

}
